package cn.edu.scau.cmi.ema.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@Service
public class Table2ColumnsOfSheetService {

	@Autowired
	private ApplicationContext applicationContext;


	// 填充引用属性
	public static void setFieldValueByFieldName(String fieldName, Object object, Object value)
			throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		// 获取obj类的字节文件对象
		Class c = object.getClass();
		// 获取该类的成员变量
		Field f = c.getDeclaredField(fieldName);
		// 取消语言访问检查
		f.setAccessible(true);
		f.set(object, value);
	}

	public Object savaEntity(Object entity) throws NoSuchMethodException, SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		String simpleName = entity.getClass().getSimpleName();
		Object service = applicationContext.getBean(simpleName + "Service");
		Method saveMethod = service.getClass().getMethod("save" + simpleName, Object.class);
		Object responseEntity = saveMethod.invoke(service, entity);

		return responseEntity;
	}



	/**
	 * 获取sheet里所有的行，一行有多条数据的会拆分成多行
	 *
	 * @param sheet
	 * @param firstRowNum 开始的行，从0开始
	 * @return
	 */
	public static List<Row> getAllRow4Sheet(Sheet sheet, int firstRowNum) {
		ArrayList<Row> rows = new ArrayList<Row>();

		int lastRowNum = sheet.getLastRowNum();
		int tempNum = lastRowNum + 1;
		for (int i = firstRowNum; i <= lastRowNum; i++) {
			Row row = sheet.getRow(i);
			if (Table2ColumnsOfSheetService.isNullRow(row))
				continue;

			List<Row> list = getRows(sheet, row, tempNum);
			tempNum += list.size();

			rows.addAll(list);
		}

		return rows;
	}

	private static List<Row> getRows(Sheet sheet, Row row, int tempNum) {
		Map<Integer, List<String>> cellValueMap = getCellValueMap(row);

		List<Row> list = new ArrayList<>();
		List<Integer> indexs = new ArrayList<>();
		indexs.addAll(cellValueMap.keySet());

		int index = 0;
		Map<Integer, String> valueMap = new HashMap<>();
		fillRow(sheet, valueMap, list, indexs, index, cellValueMap, tempNum);

		return list;
	}

	private static void fillRow(Sheet sheet, Map<Integer, String> valueMap, List<Row> rowList, List<Integer> indexs, int index,
			Map<Integer, List<String>> cellValueMap, int tempNum) {
		Integer i = indexs.get(index);
		List<String> list = cellValueMap.get(i);
		for (String s : list) {
			valueMap.put(i, s);
			if (index >= indexs.size() - 1) {
				Row newRow = sheet.createRow(tempNum + rowList.size());
				map2Row(newRow, rowList, valueMap);
			} else {
				fillRow(sheet, valueMap, rowList, indexs, index + 1, cellValueMap, tempNum);
			}
		}
	}

	private static void map2Row(Row row, List<Row> list, Map<Integer, String> valueMap) {
		for (Entry<Integer, String> e : valueMap.entrySet()) {
			Cell cell = row.createCell(e.getKey());
			cell.setCellValue(e.getValue());
		}
		list.add(row);
	}

	private static Map<Integer, List<String>> getCellValueMap(Row row) {
		Map<Integer, List<String>> map = new HashMap<>();
		for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
			Cell cell = row.getCell(i);
			String value = getCellValue(cell);
			List<String> cellValueList = getCellValue(value);
			map.put(i, cellValueList);
		}
		return map;
	}

	// 划分值
	private static List<String> getCellValue(String value) {
		ArrayList<String> list = new ArrayList<String>();
		value = value.replaceAll("或", ",");
		value = value.replaceAll("，", ",");
		String[] split = value.split(",");
		for (String s : split) {
			list.add(s.trim());
		}
		return list;
	}

	// 查看是否为空行
	public static boolean isNullRow(Row row) {
		if (row == null) return true;

		for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
			Cell cell = row.getCell(i);

			if (cell == null) continue;

			String value = getCellValue(cell);

			if (value != null && !value.trim().equals("")) { // 单元格不为空
				// 不是空行
				return false;
			}
		}
		// 是空行
		return true;
	}

	private static String getCellValue(Cell cell) {
		String value;
		if (cell.getCellType() == CellType.NUMERIC) {
			String s = String.valueOf(cell.getNumericCellValue());
			value = s.substring(0, s.indexOf('.'));
		} else {
			cell.setCellType(CellType.STRING);
			value = cell.getStringCellValue();
		}
		return value;
	}

}
